
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :summary-method="(e)=>summaryMethod(e, tableOption)"
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
      >
        <!-- <template
          slot="searchMenu"
          slot-scope="{row,size}"
        >
          <el-button v-if="permissionList.export" @click="exportClick(row)">导出</el-button>
        </template> -->
        <template slot="menuRight">
          <el-button
            v-if="permissionList.generate"
            type="primary"
            size="small"
            @click="openDataExport"
          >生成日报表</el-button>
          <!-- <el-button
            v-if="permissionList.export"
            size="small"
            @click="exportClick"
          >导出</el-button> -->
          <el-button
            v-if="permissionList.export"
            type="primary"
            size="small"
            @click="exportOpen"
            >导出</el-button
          >
        </template>
      </avue-crud>
      <open-dialog
        :DialogVisible.sync="editVisableDialog"
        title="生成日报表"
        width="60%"
      >
        <el-form label-width="300px" v-if="editVisableDialog">
          <avue-form
            v-model="createForm"
            :option="cycleOptions"
            style="margin-bottom: 40px"
          ></avue-form>
          <div class="bottom-menu-report">
            <el-button type="primary" :loading="loading" @click="createdataExport">生成</el-button>
            <el-button type="primary" @click="editVisableDialog = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>

      <open-dialog
        :DialogVisible.sync="exportVisableDialog"
        title="导出"
        width="40%"
      >
        <el-form label-width="60px" v-if="exportVisableDialog">
          <avue-form
            v-model="formCreate"
            :option="exportOption"
            style="margin-bottom: 40px"
          ></avue-form>
          <div class="bottom-menu-report">
            <el-button type="primary" @click="exportClick()">确认</el-button>
            <el-button type="primary" @click="exportVisableDialog = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchLineList } from '@/api/rca/dict'
import { fetchList, dataExport, generate } from '@/api/rca/swckstationdailyreportoriginal'
import { tableOption } from '@/const/crud/rca/swckstationdailyreportoriginal'
import { handleExcelResponse, getQueryString } from "@/util/util";
import { dateFormat } from '@/util/date'
import { mapGetters } from 'vuex'
import { summaryMethod } from '@/const/crud/rca/common'

export default {
  name: 'swckstationdailyreportoriginal',
  data () {
    return {
      searchForm: {
        tradeDate: dateFormat(new Date(), 'yyyy-MM-dd'),
        lineCode: '9',
      },
      //createForm: {},
      createForm: {
        settleCycle: null,
        lineCodes: "",
      },
      tableData: [],
      loading: false,
      tableLoading: false,
      tableOption: tableOption,
      summaryMethod,
      lineOptions: [],
      editVisableDialog: false,
      exportVisableDialog: false,
      formCreate: {},
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList () {
      return {
        export: this.vaildData(this.permissions.sw_ck_station_daily_report_original_export, false),
        generate: this.vaildData(this.permissions.sw_ck_station_daily_report_generate, false),
      };
    },
    cycleOptions() {
      return {
        emptyBtn: false,
        submitBtn: false,
        column: [{
          label: "生成日期",
          prop: "settleCycle",
          type: "daterange",
          valueFormat: 'yyyy-MM-dd',
          rules: [{
            required: true,
            message: "请选择日期",
            trigger: "blur"
          }],
        }, {
          label: '线路',
          type: "select",
          prop: 'lineCodes',
          props: {
            label: 'name',
            value: 'code'
          },
	  hide:true,
	  display:false,
          multiple: true,//多选控制
          dicUrl: '/support/swparamline/dictsecondnamecase'
        }]
        // column: [ {
        //   "type": "date",
        //   "label": "开始日期",
        //   "prop": "startDate",
        //   format: 'yyyy-MM-dd',
        //   valueFormat: 'yyyy-MM-dd',
        //   rules: [
        //     {
        //       required: true,
        //       message: '请选择开始日期',
        //       trigger: 'blur'
        //     }
        //   ]
        // }, {
        //   "type": "date",
        //   "label": "结束日期",
        //   "prop": "endDate",
        //   format: 'yyyy-MM-dd',
        //   valueFormat: 'yyyy-MM-dd',
        //   rules: [
        //     {
        //       required: true,
        //       message: '请选择结束日期',
        //       trigger: 'blur'
        //     }
        //   ]
        // }]
      }
    },
    exportOption(){
      return {
        emptyBtn: false,
        submitBtn: false,
        column: [{
          "type": "date",
          "label": "开始日期",
          "prop": "startDate",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '请选择开始日期',
              trigger: 'blur'
            }
          ]
        }, {
          "type": "date",
          "label": "结束日期",
          "prop": "endDate",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '请选择结束日期',
              trigger: 'blur'
            }
          ]
        },{
          type: "select",
          label: "线路",
          prop: "lineCodes",
          props: {
            label: 'name',
            value: 'code'
          },
	  hide:true,
	  display: false,
          filterable: true,
          dicUrl: "/support/swparamline/dictsecondnamecase",
          multiple: true,//多选控制
          rules: [
            {
              required: true,
              message: "请选择线路"
            }
          ],
        }]
      }
    }
  },
  created () {
    this.loadLine()
  },
  methods: {
    /*
    cellStyle({ row, column, rowIndex,columnIndex }) {
      
      //只给序号和站点标红
      if(1==columnIndex || 2==columnIndex){
        if (row.auditStatus == 0) {
          return {
            color: "red",
          };
        }
      }
      
    },*/
    openDataExport () {
      this.editVisableDialog = true;
    },
    async createdataExport () {
      // if(!this.createForm){
      //   this.$message.error('日期不能为空')
      //   return false;
      // }
      if(!this.createForm.settleCycle){
        this.$message.error('日期不能为空')
        return false;
      }
      const [startDate, endDate] = this.createForm.settleCycle
      const lineCodes = this.createForm.lineCodes
      this.loading = true;
      
      await generate({startDate, endDate, lineCodes})
        .then(data => {
          this.$message.success('操作成功!')
          this.editVisableDialog=false
          this.refreshChange()
          this.loading = false;
        }).catch(error=> {
          if(error.message.indexOf('timeout')!=-1){
            this.$message.warning('报表生成需要一定时间，请稍后查看!')
            this.editVisableDialog=false
            this.refreshChange()
            this.loading = false;
          }else{
            this.$message.error('操作失败!')
            this.refreshChange()
            this.loading = false;
          }
        });
      // await generate({startDate, endDate});
      // this.$message.success('操作成功！报表生成需要一定时间，请稍后查看')
      // this.editVisableDialog=false
      // this.refreshChange()
      // this.loading = false;

      // this.loading = true;
      // generate(this.createForm)
      //   .then(data => {
      //     this.$message.success('操作成功！报表生成需要一定时间，请稍后查看')
      //     this.editVisableDialog=false
      //     this.refreshChange()
      //     this.loading = false;
      //   }).catch(() => {
      // });
    },
    async loadLine () {
      const { data } = await fetchLineList({})
      this.lineOptions = data.data || []
    },
    async getList (params = {}) {
      if (!this.searchForm.tradeDate) {
        this.$message.error('结算时间不能为空')
        return
      }      
     /* if (!this.searchForm.lineCode) {
        this.$message.error('线路不能为空')
        return
      }*/
      this.tableLoading = true;
      try {
        const response = await fetchList(
          Object.assign(
            params,
            this.searchForm,
          )
        );
        this.tableData = response.data.data;
        this.tableLoading = false;
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
      } catch (e) {
        this.tableLoading = false;
      }
    },
    async searchChange (form, done) {
      this.searchForm = { ...form, };
      try {
        await this.getList(this.searchForm);
      } finally {
        done();
      }
    },
    refreshChange () {
      this.getList()
    },
    exportOpen(){
      this.exportVisableDialog = true;
    },
    async exportClick () {
      let loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      })
      try {
        const res = await dataExport(this.formCreate);
        if(res.data.size==0){
          this.$message.error('所选时间范围内暂无数据导出，请重新选择！')
        }
        handleExcelResponse(res);
      } finally {
        loading.close();
      }
    },
    // async exportClick (row) {
    //   // await this.searchChange(row, () => { });
    //   this.dataExport();
    // },
    // async dataExport () {
    //   if (!this.searchForm.tradeDate) {
    //     this.$message.error('结算时间不能为空')
    //     return
    //   }
    //   if (!this.searchForm.lineCode) {
    //     this.$message.error('线路不能为空')
    //     return
    //   }
    //   let loading = this.$loading({
    //     lock: true,
    //     text: "Loading",
    //     spinner: "el-icon-loading",
    //     background: "rgba(0, 0, 0, 0.7)"
    //   })
    //   try {
    //     const res = await dataExport(this.searchForm);
    //     // const line = this.lineOptions.find(i => i.code === lineCode)
    //     // handleExcelResponse(res, `[${tradeDate}]${line.name}导出.xlsx`);
    //     handleExcelResponse(res);
    //   } finally {
    //     loading.close();
    //   }
    // },
    searchReset () {
      this.getList();
    },
  }
}
</script>
<style lang="scss">
.bottom-menu-report {
  margin-top: -30px;
  text-align: center;
}
</style>
